package leetcode.code0399;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import leetcode.IDebug;

public class Solution implements IDebug {

	public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
		int len = values.length;
		Map<String, List<String>> nexts = new HashMap<>();
		Map<String, Map<String, Double>> value = new HashMap<>();
		for (int i = 0; i < len; i++) {
			List<String> equ = equations.get(i);
			String a = equ.get(0), b = equ.get(1);
			double val = values[i];
			List<String> nexta = nexts.getOrDefault(a, new ArrayList<>());
			List<String> nextb = nexts.getOrDefault(b, new ArrayList<>());
			nexta.add(b);
			nextb.add(a);
			nexts.put(a, nexta);
			nexts.put(b, nextb);
			Map<String, Double> valueab = value.getOrDefault(a, new HashMap<>());
			Map<String, Double> valueba = value.getOrDefault(b, new HashMap<>());
			valueab.put(b, val);
			valueba.put(a, 1 / val);
			value.put(a, valueab);
			value.put(b, valueba);
		}
		int len1 = queries.size();
		double[] ans = new double[len1];
		for (int i = 0; i < len1; i++) {
			List<String> query = queries.get(i);
			String c = query.get(0), d = query.get(1);
			double curAns = -1;
			if (!nexts.containsKey(c) || !nexts.containsKey(d)) {
				ans[i] = -1;
				continue;
			}
			Queue<Object[]> queue = new LinkedList<>();
			queue.add(new Object[] { c, 1 });
			Set<String> done = new HashSet<>();
			while (!queue.isEmpty()) {
				Object[] cur = queue.poll();
				String param = String.valueOf(cur[0]);
				double val = Double.valueOf(String.valueOf(cur[1]));
				if (param.equals(d)) {
					curAns = val;
					break;
				}
				List<String> next = nexts.get(param);
				if (next == null) {
					continue;
				}
				for (String nex : next) {
					if (done.contains(nex)) {
						continue;
					}
					done.add(nex);
					Double v = value.get(param).get(nex);
					queue.add(new Object[] { nex, val * v });
				}
			}
			ans[i] = curAns;
		}
		return ans;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
